﻿#pragma once
#include "ODSocket.h"
#include "cocos2d.h"
#include "Message.h"
#include <thread>
#include <vector>
#include <List>
using namespace std;

enum SocketState{
	Disconnected,
	Connected
};

class SocketThread
{
public:
	function<void(void)> onConnected;
	function<void(void)> onConnectFailed;
	function<void(void)> onConnectionClosed;
	function<void(void)> onNetworkError;
	~SocketThread(void);
	static SocketThread*   getInstance();
	int start(string& ip, int port);
	ODSocket getSocket();
	SocketState state;// //0 表示连接成功 1 表示连接失败

	ODSocket csocket;
	void stop();//函数中止当前线程。
	//int sendmessage(Message* msg,bool insertFirst=false);
	int sendmessage(Message* msg, bool insertFirst =false);
	void start_send_thread();
	string ip;
	int port;
	static int SendCount;
	bool NeedReConnection;
	bool Reconnection();
	int reconnectTimes;
	static bool InBackground;
private:
	//线程锁

	/*pthread_mutex_t _messageQueueMutex;
	pthread_t pid;
	pthread_t pid_send;*/
	//mutex _messageQueueMutex;
	mutex _messageQueueMutex;
	thread threadSend;
	thread _thread;
	static bool quit;
	static void* start_thread(void *);//静态成员函数,相当于C中的全局函数
	//static void* send_fun(void *);//静态成员函数,相当于C中的全局函数
	//static void* send_fun(void *);
	static void* send_fun(void*);
	SocketThread(void);

	static ByteBuf send_buf;
	static ByteBuf recv_buf;

	//list<Message*> messages;
	list<Message*>messages;
	long lastsend_time;
	static string bytestohexstring(char* bytes, int bytelength);
private:
	//static SocketThread* m_pInstance;
	static SocketThread* m_pInstance;
};

